<template>
  <div
    style="width: 48%; height: 320px; margin-right: auto"
    ref="chartRef"
  ></div>
</template>
<script setup lang="ts">
import {
  onMounted,
  ref,
  watch,
  nextTick,
  onBeforeUnmount,
  computed,
} from "vue";
import echarts from "@/plugins/echarts";
import { OrdersData } from "@/types/statistics";
import type { ECOption } from '@/plugins/echarts'

const props = defineProps<{
  ordersData: OrdersData;
}>();
const ordersData = ref(props.ordersData);
// 图表dom实例
const chartRef = ref<HTMLElement | null>(null);
let resizeObserver: ResizeObserver | null = null;
let chart: echarts.ECharts;

const splitDateList = computed(() =>
  ordersData.value.dateList ? ordersData.value.dateList.split(",") : []
);

const splitOrderCountList = computed(() =>
  ordersData.value.orderCountList
    ? ordersData.value.orderCountList.split(",")
    : []
);

const splitValidOrderCountList = computed(() =>
  ordersData.value.validOrderCountList
    ? ordersData.value.validOrderCountList.split(",")
    : []
);
const initChart = () => {
  chart = echarts.init(chartRef.value, "purple-passion");
  chart.setOption<ECOption>({
    title: {
      text: "订单统计",
      left: "10",
      top: "15",
      textStyle: {
        fontSize: "16px",
      },
    },
    legend: {
      show: true,
      orient: "horizontal",
      x: "center",
      y: "20",
      itemGap: 10,
      data: ["订单总数", "有效订单"],
    },
    grid: {
      top: "20%",
      left: "30",
      right: "30",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: splitDateList.value,
      boundaryGap: false,
      axisLine: {
        //X轴线颜色
        lineStyle: {
          color: "#666",
          width: 1, //x轴线的宽度
        },
      },
    },
    tooltip: {
      trigger: "axis",
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "订单总数",
        data: splitOrderCountList.value,
        type: "line",
        smooth: true,
        showSymbol: false, //未显示鼠标上移的圆点
      },
      {
        name: "有效订单",
        data: splitValidOrderCountList.value,
        type: "line",
        smooth: true,
        showSymbol: false, //未显示鼠标上移的圆点
      },
    ],
  });
  if (!resizeObserver) {
    resizeObserver = new ResizeObserver(() => {
      if (chart) {
        chart.resize();
      }
    });
    resizeObserver.observe(chartRef.value!);
  }
};
watch(
  () => props.ordersData,
  (newVal, _oldVal) => {
    nextTick(() => {
      ordersData.value = newVal;
      echarts.dispose(chart);
      initChart();
    });
  },
  { immediate: true }
);
onMounted(() => {
  initChart();
});
onBeforeUnmount(() => {
  if (chart) {
    echarts.dispose(chart);
  }
});
</script>
<style scoped lang="scss">
#main {
  background: #fff;
  border-radius: 5px;
}
</style>
